package com.onlineclass.onlineclassmanagement.controller;


import com.onlineclass.beas.ResultObject;
import com.onlineclass.beas.User;
import com.onlineclass.onlineclassmanagement.annoation.PassToken;
import com.onlineclass.onlineclassmanagement.feign.UserFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/user")
public class UserController {

    UserFeign feign;

    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    @PassToken
    public ResultObject login(User user, HttpServletResponse response){
        try{
            User u = feign.login(user);
            if (u != null){
                System.out.println(u);
                String token = User.getToken(u);
                redisTemplate.opsForValue().set(token,u);
                Cookie cookie = new Cookie("token",User.getToken(u));
                cookie.setPath("/");
                cookie.setDomain("localhost");
                response.addCookie(cookie);
                return new ResultObject(1,"right","");
            }else{
                return new ResultObject(0,"用户错误或密码错误","");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询错误");
            return null;
        }
    }

    @RequestMapping("/selectUserInfo")
    @PassToken
    public ResultObject selectUserInfo(){
        return feign.selectUserInfo();
    }


}
